package com.sky.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

@ServerEndpoint("/ws/{sid}")
@Component
public class WebSocket {

    //    private static List<Session> sessionList = new ArrayList<>();
    private static Map<String, Session> map = new HashMap<>();

    @OnOpen //连接
    public void onOpen(@PathParam("sid") String sid, Session session) {
        System.out.println("有用户连接了: " + session);
        map.put(sid, session);
        //sessionList.add(session);  //将用户的session添加进集合
    }

    @OnMessage //接收信息
    public void onMessage(String msg) {
        System.out.println("用户发来信息 : " + msg);
    }

    @OnClose //断开连接
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("用户" + map.get(sid) + "断开连接");
        map.remove(sid);
    }

    /**
     * 群发信息---管理端响应
     *
     * @param msg
     * @return
     */
    public void sendAllServer(String msg) {
//        for (Session session : sessionList) {
//            try {
//                session.getBasicRemote().sendText(msg);
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }

        Collection<Session> values = map.values();
        for (Session session : values) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
